import base64
from datetime import datetime
import urllib
import wsgiref.handlers
import logging

from google.appengine.ext import webapp
from google.appengine.ext import db

key = "RTGBN<LHFDLJIOM"
auth = base64.b64encode('showmydebianip'+':')

class IPModel(db.Model):
    addr = db.StringProperty()
    t = db.DateTimeProperty()

class IP(webapp.RequestHandler):
    def check_auth(self):
        auth_req = self.request.headers.get('Authorization')
        if auth_req and auth_req.strip().split(' ')[1] == auth:
            return True
        self.error(401)
        self.response.headers['WWW-Authenticate'] = 'Basic realm="ip ddns"'
        return False
    def post(self):
        if self.request.get('key') != key:
            self.error(404)
            return
        ip = IPModel.all().fetch(1)
        if len(ip) == 0:
            ip = IPModel()
        else:
            ip = ip[0]
        ip.addr = self.request.remote_addr
        ip.t = datetime.now()
        ip.put()
        self.response.headers['Content-Type']='text/html'
        self.response.out.write(ip.addr)
        return
    def get(self):
        if not self.check_auth():
            return
        ip = IPModel.all().fetch(1)
        self.response.headers['Content-Type']='application/json'
        if len(ip) == 0:
            ip = None
            error = True
            msg = "No IP registered"
            self.response.out.write('{"error": "%s",\n"ip": "None",\n"msg":"%s"\n}' % (error, msg))
        else:
            ip = ip[0]
            error = False
            msg = "Registered IP is %s, Time is %s (UTC)"%(ip.addr,str(ip.t))
            self.response.out.write('{"error": "%s",\n"ip": "%s",\n"msg":"%s"\n}' % (error, ip.addr, msg))
        return
        
def main():
    application = webapp.WSGIApplication(
                           [('/ip/?', IP)],
                           debug=False)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

